package com.koo.modules.quartz.server.impl;

import com.koo.common.exception.RRException;
import com.koo.common.utils.MyDateUtil;
import com.koo.common.utils.MyStrUtil;
import com.koo.modules.gy.entity.*;
import com.koo.modules.gy.service.*;
import com.koo.modules.quartz.constant.B2BConstant;
import com.koo.modules.quartz.server.BaseThirdDataService;
import com.koo.modules.quartz.util.ChangeUtil;
import com.koo.modules.quartz.util.SqlJDBCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class GYThirdDataServiceImpl implements BaseThirdDataService {

    @Autowired
    private GyStoreInfoService gyStoreInfoService;
    @Autowired
    private GyProductService gyProductService;
    @Autowired
    private GyOrderOutService gyOrderOutService;
    @Autowired
    private GyInspectionOrderService gyInspectionOrderService;
    @Autowired
    private GyInspectionOrderDetailService gyInspectionOrderDetailService;


    @Override
    public void storeDataTransport() {
        //验证当前的企业是否开启了同步机制
        if (!checkNeedThirdData()) {
            return;
        }

        Date maxCreateDate = gyStoreInfoService.selectMaxCreateDate();
        String addDate = null;
        if (MyStrUtil.isNotEmpty(maxCreateDate)) {
            addDate = MyDateUtil.formatCurrDateTime();
        }
        //1.从广缘查询数据
        String sql = B2BConstant.GY_PULL_STORE_SQL.getSql();
        if (MyStrUtil.isNotEmpty(addDate)) {
            sql = sql.replace("{WHERE_LIST}", " WHERE CONVERT (VARCHAR(25), UpdateDate, 120) >= '" + addDate + "' ");
        } else {
            sql = sql.replace("{WHERE_LIST}", " ");
        }
        Connection connection = null;
        List<GyStoreInfoEntity> infos = new ArrayList<>();
        try {
            connection = SqlJDBCUtil.getConnection(B2BConstant.GY.getCompanyCode());
            ResultSet rs = SqlJDBCUtil.execQuery(sql, connection);
            infos = ChangeUtil.changeResultToList(rs, GyStoreInfoEntity.class);
        } finally {
            SqlJDBCUtil.commit(connection);
        }
        //2.插入到对应前缀的门店表
        //1.删除已经存在的
        //2.批量插入
        //删除和插入在service事务执行
        if (infos.isEmpty()) {
            return;
        }
        gyStoreInfoService.saveBatch(infos);
    }

    @Override
    public void productDataTransport() {
        if (!checkNeedThirdData()) {
            return;
        }
        Date maxModifyDate = gyProductService.selectMaxCreateDate();
        String addDate = null;
        if (MyStrUtil.isNotEmpty(maxModifyDate)) {
            addDate = MyDateUtil.formatCurrDateTime();
        }
        //1.从广缘查询商品数据
        String sql = B2BConstant.GY_PULL_PRODUCT_SQL.getSql();
        if (MyStrUtil.isNotEmpty(addDate)) {
            sql = sql.replace("{WHERE_LIST}", " WHERE CONVERT (VARCHAR(25), A.updateDate, 120) >= '" + addDate + "' ");
        } else {
            sql = sql.replace("{WHERE_LIST}", " ");
        }
        Connection connection = null;
        List<GyProductEntity> products = new ArrayList<>();
        try {
            connection = SqlJDBCUtil.getConnection(B2BConstant.GY.getCompanyCode());
            ResultSet resultSet = SqlJDBCUtil.execQuery(sql, connection);
            products = ChangeUtil.changeResultToList(resultSet, GyProductEntity.class);
        } finally {
            SqlJDBCUtil.commit(connection);
        }
        if (products.isEmpty()) {
            return;
        }
        //2.插入到对应前缀的商品表
        gyProductService.saveBatch(products);
    }

    @Override
    public void outOrderDataTransport() {
        if (!checkNeedThirdData()) {
            return;
        }
        String maxHeadQuarterAllotDate = gyOrderOutService.selectMaxHeadQuarterAllotDate();
        if (MyStrUtil.isEmpty(maxHeadQuarterAllotDate)) {
            throw new RRException("同步出库单时出库时间不能为空,否则查询全部数据!!!");
        }
        //1.从广缘查询出库单
        String sql = B2BConstant.GY_PULL_OUT_ORDER_SQL.getSql().replace("{WHERE_LIST}", " AND CONVERT (VARCHAR(25), a.jzrq, 21) > '" + maxHeadQuarterAllotDate + "' ");
        Connection connection = null;
        List<GyOrderOutEntity> orderOuts = new ArrayList<>();
        try {
            connection = SqlJDBCUtil.getConnection(B2BConstant.GY.getCompanyCode());
            ResultSet resultSet = SqlJDBCUtil.execQuery(sql, connection);
            orderOuts = ChangeUtil.changeResultToList(resultSet, GyOrderOutEntity.class);
        } finally {
            SqlJDBCUtil.commit(connection);
        }
        if (orderOuts.isEmpty()) {
            return;
        }
        //2.插入到对应前缀的出库表
        gyOrderOutService.saveBatch(orderOuts);
    }


    @Override
    public boolean checkNeedThirdData() {
        return ChangeUtil.checkNeedThridDataService(B2BConstant.GY.getCompanyCode());
    }

    @Override
    public void convertInspectionOrderData() {
        if (!checkNeedThirdData()) {
            return;
        }
        //1.查询未转换的单据单号和总金额,根据单号查询主单和明细
        List<GyInspectionOrderEntity> outOrders = gyInspectionOrderService.listInspectionOrders(B2BConstant.MAX_CONVERT_OUT_ORDER_LIMIT_SIZE.getNumber());
        //根据单号,查询该单号是否存在,存在则忽略,不存在,查询明细
        List<GyInspectionOrderDetailEntity> orderDetails = new ArrayList<>();
        Iterator<GyInspectionOrderEntity> iterator = outOrders.iterator();
        while (iterator.hasNext()) {
            GyInspectionOrderEntity order = iterator.next();
            boolean hasOrder = gyInspectionOrderService.findHasOrderByHeadNo(order.getHeadQuarterAllotNo());
            if (hasOrder) {
                iterator.remove();
            } else {
                //查询明细,添加明细到待插入列表.
                List<GyInspectionOrderDetailEntity> listDetails = gyInspectionOrderDetailService.listInspectionOrderDetails(order.getHeadQuarterAllotNo());
                orderDetails.addAll(listDetails);
            }
        }
        //2.插入主单到xxInspectionOrder,明细到xxInspectionOrderDetail //3.更新已插入的单号的状态
        //插入主表和明细.
        if (outOrders.isEmpty()) {
            return;
        }
        gyInspectionOrderService.insertByListAndUpdateState(outOrders, orderDetails);
    }

    @Override
    public void storeDataToAdminTransport() {

    }

    @Override
    public void uploadMemberData() {

    }

    @Override
    public void uploadSaleData() {

    }

    @Override
    public void uploadStockData() {

    }
}
